#!/usr/bin/env node

/**
 * 自动设置Windows计划任务的脚本
 * 用于配置IPTV爬虫的定时执行
 */

const { exec } = require('child_process');
const path = require('path');
const fs = require('fs');

// 获取当前脚本的绝对路径
const scriptDir = __dirname;
const crawlerPath = path.join(scriptDir, 'iptvCrawler.js');

// 检查文件是否存在
if (!fs.existsSync(crawlerPath)) {
  console.error(`错误: 找不到爬虫脚本 ${crawlerPath}`);
  process.exit(1);
}

// 构建计划任务XML
function buildTaskXml() {
  // 获取Node.js可执行文件路径
  const nodePath = process.execPath;
  const taskName = 'IPTV爬虫定时任务';
  
  return `<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Description>每周二零点自动执行IPTV直播源爬虫</Description>
  </RegistrationInfo>
  <Triggers>
    <CalendarTrigger>
      <StartBoundary>2023-01-01T00:00:00</StartBoundary>
      <Enabled>true</Enabled>
      <ScheduleByWeek>
        <DaysOfWeek>
          <Tuesday/>
        </DaysOfWeek>
        <WeeksInterval>1</WeeksInterval>
      </ScheduleByWeek>
    </CalendarTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <LogonType>InteractiveToken</LogonType>
      <RunLevel>LeastPrivilege</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>true</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>true</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>false</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>true</WakeToRun>
    <ExecutionTimeLimit>PT1H</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>${nodePath}</Command>
      <Arguments>${crawlerPath}</Arguments>
      <WorkingDirectory>${scriptDir}</WorkingDirectory>
    </Exec>
  </Actions>
</Task>`;
}

// 创建临时XML文件
function createTempXmlFile(xmlContent) {
  const tempXmlPath = path.join(scriptDir, 'iptv-task.xml');
  // 添加UTF-16LE的BOM标记并保存XML文件
  const bom = Buffer.from([0xFF, 0xFE]);
  const contentBuffer = Buffer.from(xmlContent, 'utf16le');
  const fileBuffer = Buffer.concat([bom, contentBuffer]);
  fs.writeFileSync(tempXmlPath, fileBuffer);
  return tempXmlPath;
}

// 注册计划任务
function registerTask(xmlPath) {
  const taskName = 'IPTV爬虫定时任务';
  const command = `schtasks /create /tn "${taskName}" /xml "${xmlPath}" /f`;
  
  console.log('正在创建计划任务...');
  
  exec(command, (error, stdout, stderr) => {
    // 删除临时XML文件
    try {
      fs.unlinkSync(xmlPath);
    } catch (e) {
      console.error('删除临时XML文件失败:', e);
    }
    
    if (error) {
      console.error('创建计划任务失败:', error);
      console.error('可能需要以管理员权限运行此脚本');
      return;
    }
    
    console.log('计划任务创建成功!');
    console.log('任务详情:');
    console.log(`- 名称: ${taskName}`);
    console.log('- 执行频率: 每周二零点');
    console.log(`- 执行命令: ${process.execPath} ${crawlerPath}`);
    console.log('- 工作目录:', scriptDir);
    console.log('\n您可以在Windows任务计划程序中查看和修改此任务。');
  });
}

// 主函数
function main() {
  console.log('===== IPTV爬虫定时任务设置 =====');
  console.log('此脚本将创建一个Windows计划任务，每周二零点自动执行IPTV爬虫。');
  
  try {
    const xmlContent = buildTaskXml();
    const xmlPath = createTempXmlFile(xmlContent);
    registerTask(xmlPath);
  } catch (error) {
    console.error('设置计划任务时出错:', error);
  }
}

// 执行主函数
main();